﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NHibernate;
using NHibernate.Linq;
using NHibernate.Criterion;

namespace ShopSpace.Infrastructure.Data.Impl
{
	internal class GenericDAO : IGenericDAO
	{

		public ISessionFactory SessionFactory
		{
			get;
			set;
		}

		private ISession Session
		{
			get
			{
				return this.SessionFactory.GetCurrentSession();
			}
		}

		public long Count<T>(Expression<Func<T, bool>> where)
		{
			throw new NotImplementedException();
		}

		public void Delete<T>(T target)
		{
			this.Session.Delete(target);
		}

		public T Find<T>(object id)
		{
			return this.Session.Get<T>(id);
		}

		public T FindFirst<T>(Expression<Func<T, bool>> where)
		{
			return this.Session.Linq<T>().First<T>(where);
		}

		public T FindUnique<T, U>(Expression<Func<T, U>> expression, U search) where T : class
		{
			//string propertyName = ReflectionHelper.GetProperty(expression).Name;
			//var criteria = this.Session.CreateCriteria(typeof(T)).Add(Restrictions.Eq(propertyName, search));
			//return criteria.UniqueResult() as T;
			throw new NotImplementedException();
		}

		public void Save<T>(T target)
		{
			this.Session.SaveOrUpdate(target);
		}

		public T[] Query<T>(Expression<Func<T, bool>> where)
		{
			return this.Session.Linq<T>().Where(where).ToArray<T>();
		}

		public IQueryable<T> AsQueryable<T>()
		{
			return this.Session.Linq<T>();
		}


		public IList<T> ListbyCriteria<T>(DetachedCriteria criteria)
		{
			return criteria.GetExecutableCriteria(this.Session).List<T>();
		}
	}
}
